package com.example.controller;

import com.example.entity.Movie;
import com.example.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/movie")
public class MovieController {

    @Autowired
    private MovieService movieService;

    // 电影列表页面
    @GetMapping("/list")
    public String list(Model model) {
        List<Movie> movies = movieService.getAllMovies();
        model.addAttribute("movies", movies);
        return "movie/list";
    }

    // 电影详情页面
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Movie movie = movieService.getMovieById(id);
        model.addAttribute("movie", movie);
        return "movie/detail";
    }

    // 添加电影页面
    @GetMapping("/add")
    public String addPage() {
        return "movie/add";
    }

    // 添加电影
    @PostMapping("/add")
    @ResponseBody
    public String add(Movie movie) {
        boolean result = movieService.addMovie(movie);
        return result ? "success" : "failed";
    }

    // 编辑电影页面
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, Model model) {
        Movie movie = movieService.getMovieById(id);
        model.addAttribute("movie", movie);
        return "movie/edit";
    }

    // 更新电影
    @PostMapping("/update")
    @ResponseBody
    public String update(Movie movie) {
        boolean result = movieService.updateMovie(movie);
        return result ? "success" : "failed";
    }

    // 删除电影
    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id) {
        boolean result = movieService.deleteMovie(id);
        return result ? "success" : "failed";
    }

    // 根据类型查询电影
    @GetMapping("/type/{types}")
    public String listByType(@PathVariable String types, Model model) {
        List<Movie> movies = movieService.getMoviesByType(types);
        model.addAttribute("movies", movies);
        model.addAttribute("types", types);
        return "movie/list";
    }
}
